package com.cqust.dao;

import com.cqust.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class StudentDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    public int insert(Student student)
    {
        String sql="insert into student(sno,name,age,major) values (?,?,?,?)";
//        sql=String.format(sql,
//                student.getSno(),
//                student.getName(),
//                student.getAge(),
//                student.getMajor());
        Object[] objects=new Object[]{
                student.getSno(),
                student.getName(),
                student.getAge(),
                student.getMajor()
        };
        jdbcTemplate.update(sql,objects);
        sql="select * from student where sid=(select max(sid) from student)";
        RowMapper<Student> rm=new BeanPropertyRowMapper<Student>(Student.class);
        Student student1=jdbcTemplate.queryForObject(sql,rm);
        student.setSid(student1.getSid());
        return student1.getSid();
    }

    public int updateById(Student student)
    {
        String sql="update student set age=? where sid=?";
        Object[] objects=new Object[]{
                student.getAge(),
                student.getSid()
        };
        jdbcTemplate.update(sql,objects);
        return 1;
    }

    public int deleteById(int id)
    {
        String sql="delete from student where sid=?";
        jdbcTemplate.update(sql,id);
        return 1;
    }

    public Student selectById(int id)
    {
        String sql="SELECT * FROM student where sid=?";
        RowMapper<Student> rm=new BeanPropertyRowMapper<Student>(Student.class);
        return jdbcTemplate.queryForObject(sql,rm,id);
    }

    public List<Student> selectByCondition(String strWhere)
    {
        String sql="SELECT * FROM student ";
        if(strWhere.trim().length()>0)
        {
            sql=sql+"where "+strWhere;
        }
        RowMapper<Student> rm=new BeanPropertyRowMapper<Student>(Student.class);
        return jdbcTemplate.query(sql,rm);
    }
}
